package com.huaboot.system.demo.rangesearch;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.domain.geo.Metrics;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.huaboot.system.demo.rangesearch.ShopData.SHOP_KEY;

/**
 * description: ShopServiceImpl
 * date: 2023/10/12 16:13
 * author: ff
 */
@Service
public class ShopServiceImpl implements ShopService{

    @Autowired
    private GeoComponent geoComponent;

    @Override
    public void syncShopLocationData() {
        List<Shop> data = ShopData.getData();
        //地理位置信息同步到Redis
        data.forEach(obj->{
            double accuracy = obj.getAccuracy().doubleValue();
            double latitude = obj.getLatitude().doubleValue();
            String id = obj.getId();
            geoComponent.geoAdd(SHOP_KEY,accuracy,latitude,id);
        });
    }

    @Override
    public Shop getShopById(String id) {
        return ShopData.getDataMap().get(id);
    }

    @Override
    public List<Shop> getShopListByLocation(Map<String, Object> user) {
        List<Shop> shopVOS = new ArrayList<>();
        // 获取用户的坐标位置
        double accuracy = (double) user.get("accuracy");
        double latitude = (double) user.get("latitude");
        String userId = "588fa28618b147fa87a904a541e7833b";

        // 将用户位置加入到Redis
        //geoComponent.geoAdd(ShopData.SHOP_KEY, accuracy, latitude, userId);
        // 获取用户附近的门店
        List<String> shopIds = geoComponent.geoRadiusByMember(ShopData.SHOP_KEY, userId, 1000000, Metrics.KILOMETERS);
        for (String shopId : shopIds) {
            //如果是当前userId则直接跳出
            if (shopId.equals(userId)) {
                continue;
            }
            //获取shop信息
            Shop shopVO = this.getShopById(shopId);
            if (shopVO ==null){
                continue;
            }
            //获取两点的距离
            double distance = geoComponent.geoDist(ShopData.SHOP_KEY, userId, shopId, Metrics.KILOMETERS).getValue();
            //保留一位小数
            distance = new BigDecimal(distance).setScale(1, RoundingMode.DOWN).doubleValue();
            shopVO.setDistance(distance);
            shopVOS.add(shopVO);
        }
        // 删除Redis中用户位置。
        //geoComponent.geoDelete(ShopData.SHOP_KEY,userId);
        //排序 返回
        return shopVOS.stream().sorted(Comparator.comparingDouble(Shop::getDistance)).collect(Collectors.toList());
    }
}
